/*++----------------------------------------------------------------------------------------------------------------------------------------------------------------------
1. 项目名称：wechat-education
2. 文件功能： apiDataFilter的定义
3. 作者：451230805@qq.com
4. 备注：
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------++*/
/*++-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
加载相关资源
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------++*/
import apiConf from '../apiConfs/api' ;

/*++-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
apiDataFilter的定义
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------++*/
class ApiDataFilter {
  constructor() {

  }

  /*++-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
  请求数据 , successCallback的唯一参数为：response，返回的json数据应该这样取得：response.body
  @apiPath : 接口路径
  @data : 同步发送的参数
  @method : get | post | jsonp
  @showLoading : 是否开启自定义的加载动画
  @showNavigationBarLoading : 是否开启小程序导航头loading
  @tips : 当请求结果异常时 是否开启message的提示
  @successCallback : 请求成功的回调处理
  @errorCallback : 请求异常的回调处理
  @completeCallback : 清酒完成就执行的回调
  -----------------------------------------------------------------------------------------------------------------------------------------------------------------------++*/
  request({apiPath, data = {}, method = 'get', dataType = 'json', contentType = 'application/json', showNavigationBarLoading = true, showLoading = true, tips = true, successCallback, errorCallback, completeCallback, loadingCallback}) {
    let requestMethod = method.toLowerCase();
    let errorProcesser = (errorCallback && typeof errorCallback === 'function') ? errorCallback : this.errorCallback;
    let Authorization = wx.getStorageSync('Authorization') ? wx.getStorageSync('Authorization') : '';
    /*++-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
    首先根据showNavigationBarLoading参数决定是否需要开启小程序导航栏的加载提示
    -----------------------------------------------------------------------------------------------------------------------------------------------------------------------++*/
    showNavigationBarLoading && wx.showNavigationBarLoading();
    wx.showLoading();
    /*++-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
    首先根据showLoading参数决定是否需要开启自定义的加载提示
    -----------------------------------------------------------------------------------------------------------------------------------------------------------------------++*/
    if (showLoading) {
      loadingCallback && typeof loadingCallback == 'function' && loadingCallback();
    }
    /*++-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
    请求参数拼装
    -----------------------------------------------------------------------------------------------------------------------------------------------------------------------++*/
    let params = {
      url: this.pathToUrl(apiPath),
      method: requestMethod,
      data,
      dataType,
      header: {
        token: Authorization,
        'MINI-INSTANCE': 1
      },
      success: function (res) {
        if (res.statusCode.toString() === '200' && res.data.code.toString() == apiConf.successStatusCode) {
          typeof successCallback == 'function' && successCallback(res.data);
        } else {
          if (tips) {

          }
          errorProcesser(res);
        }
      },
      fail: function (error) {
        errorProcesser(error);
      },
      complete: function () {
        showNavigationBarLoading && wx.hideNavigationBarLoading();
        typeof completeCallback == 'function' && completeCallback();
        wx.hideLoading();
      }
    };

    if (requestMethod == 'post') {
      if (contentType) {
        Object.assign(params.header, {'Content-Type': contentType});
      }
    }
    wx.request(params);
  }

  /*++-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
  请求错误处理方法
  -----------------------------------------------------------------------------------------------------------------------------------------------------------------------++*/
  errorCallback(error) {
    if (error.data.code === 700 || error.data.code === 701) {
      try {
        wx.removeStorageSync('Authorization');
      } catch (e) {
        // Do something when catch error
      }
      // wx.navigateTo({ url: `/pages/home/login` });
    } else {
      if (error.data && error.data.message) {
        wx.showToast({
          title: error.data.message.replace(/<\/?.+?>/g, ""),
          icon: 'none',
          duration: 1000
        });
      }
    }
  }

  /*++-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
  根据apiPath返回apiUrl
  @apiPath：从api配置中suffix往下层写如："example.rent.detail"
  -----------------------------------------------------------------------------------------------------------------------------------------------------------------------++*/
  pathToUrl(apiPath) {
    let pathArray = apiPath.split('.');
    let suffix = apiConf.suffix;
    for (let n = 0; n < pathArray.length; n++) {
      suffix = suffix[pathArray[n]];
    }
    if (suffix === undefined) suffix = '';
    return apiConf.prefix[apiConf.dataStageEnv] + '/' + suffix;
  }

  /*++-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
 整个工具定义结束
 -----------------------------------------------------------------------------------------------------------------------------------------------------------------------++*/
}

export default new ApiDataFilter;
